<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        align-center
        :space="200"
        :active="activeIndex-0
      
      "
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          style="margin-bottom: 30px;"
          :before-leave="cateTabsChange"
          @tab-click="cateTabsClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="cateHandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTabsData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  :label="item1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabsData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片要上传到的后台Api地址 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片的弹出层 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewPath" alt />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 控制图片预览层的弹出
      dialogVisible: false,
      // 图片预览要显示的图片路径
      previewPath: "",
      // 设置上传图片请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 上传图片的地址
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      // 被激活的tab栏的name
      activeIndex: 0,
      // form表单绑定的数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        // 图片数组
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      // 商品分类的数据 多级联动框
      cateList: [],
      // 多级联动框的设置属性
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 商品动态参数
      manyTabsData: [],
      onlyTabsData: []
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data;
    },
    cateHandleChange() {
      if (this.addForm.goods_cat.length !== 3)
        return (this.addForm.goods_cat.length = []);
    },
    cateTabsChange(activeName, oldActiveName) {
      // console.log("即将进入的标签页的名字是" + activeName);
      // console.log("即将离开的标签页的名字是" + oldActiveName);
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
      // return false;
    },
    async cateTabsClick() {
      // console.log(this.activeIndex);
      if (this.activeIndex == 1) {
        const { data: res } = await this.$http.get(
          "categories/" + this.cateId + "/attributes",
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 商品动态参数
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          for (var i = 0; i < item.attr_vals.length; i++) {
            if (!item.attr_vals[i]) {
              item.attr_vals.splice(i, 1);
              i = i - 1;
            }
          }
        });
        this.manyTabsData = res.data;
        // console.log(this.manyTabsData);
      } else if (this.activeIndex == 2) {
        const { data: res } = await this.$http.get(
          "categories/" + this.cateId + "/attributes",
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 商品静态属性
        this.onlyTabsData = res.data;
        console.log(this.onlyTabsData);
      }
    },
    // 监听图片上传成功的事件
    handleSuccess(res) {
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      const obj = { pic: res.data.tmp_path };
      this.addForm.pics.push(obj);
    },
    // 处理移除图片的操作
    handleRemove(file) {
      // 获取到要删除图片的临时路径
      const filePath = file.response.data.tmp_path;
      // 根据临时路径找到pics数组中的索引
      const index = this.addForm.pics.findIndex(x => x.pic === filePath);
      this.addForm.pics.splice(index, 1);
    },
    // 处理图片预览效果的
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.dialogVisible = true;
    },
    // 提交添加商品的按钮点击事件
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error("请填写必要的表单项");
        this.manyTabsData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          };
          this.addForm.attrs.push(newInfo);
        });
        this.onlyTabsData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.addForm.attrs.push(newInfo);
        });
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // console.log(form);
        // 发起添加商品的请求
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-dialog img {
  width: 100%;
  height: 100%;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>

